package com.gss.plugin.mp.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: DYang
 * @since: 2023/8/23
 * @description:
 */
@Component
public class MybatisPlusFillHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        List<DefaultData> list = DefaultData.getAllDefaultData("insert");
        for (DefaultData defaultValue : list) {
            Object data = defaultValue.data;
            if (data instanceof Date) {
                this.setFieldValByName(defaultValue.fieldName,new Date(),metaObject);
            }else {
                this.setFieldValByName(defaultValue.fieldName,defaultValue.data,metaObject);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        List<DefaultData> list = DefaultData.getAllDefaultData("update");
        for (DefaultData defaultValue : list) {
            Object data = defaultValue.data;
            if (data instanceof Date) {
                this.setFieldValByName(defaultValue.fieldName,new Date(),metaObject);
            }else {
                this.setFieldValByName(defaultValue.fieldName,defaultValue.data,metaObject);
            }
        }
    }

    /**
     * 默认值枚举
     */
    public static enum DefaultData{
        CREATE_TIME("insert","createTime", Date.class,new Date()),
        DEL("insert","del", Integer.class,0),
        UPDATE_TIME("update","updateTime", Date.class,new Date()),
        ;
        protected String type;
        protected String fieldName;
        protected Class<?> fieldClass;
        protected Object data;

        DefaultData(String type, String fieldName, Class<?> fieldClass, Object data) {
            this.type = type;
            this.fieldName = fieldName;
            this.fieldClass = fieldClass;
            this.data = data;
        }

        public static List<DefaultData> getAllDefaultData(String type){
            List<DefaultData> list = new ArrayList<>();
            DefaultData[] values = values();
            for (DefaultData value : values) {
                if (value.type.equals(type)) {
                    list.add(value);
                }
            }
            return list;
        }
    }
}
